package com.eoe.wiki.utils;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteException;
import android.net.Uri;
import android.widget.Toast;

public final class SqliteWrapper {

	public final static String SQLITE_EXCEPTION_DETAIL_MESSAGE = "unable to open database file.";
	private SqliteWrapper(){
		
	}
	
	private static boolean isLowMemoey(SQLiteException e){
		return e.getMessage().equals(SQLITE_EXCEPTION_DETAIL_MESSAGE);
	}
	
	public static void checkSqliteException(Context context,SQLiteException e){
		if(isLowMemoey(e)){
			Toast.makeText(context, "com.android.inernal.R.string.low_memory", Toast.LENGTH_SHORT).show();
		}else{
			throw e;
		}
	}
	
	public static Cursor query(Context context, ContentResolver resolver, Uri uri,
            String[] projection, String selection, String[] selectionArgs, String sortOrder){
		try {
			return resolver.query(uri, projection, selection, selectionArgs, sortOrder);
		} catch (SQLiteException e) {
			// TODO Auto-generated catch block
			L.e("Catch a SQLiteException when query: " + e);
			checkSqliteException(context, e);
			return null;
		}
	}
	
	public static boolean requery(Context context,Cursor cursor){
		try {
			return cursor.requery();
		} catch (SQLiteException e) {
			// TODO Auto-generated catch block
			L.e("Catch a SQLiteException when query: " + e);
			checkSqliteException(context, e);
			return false;
		}
	}
	
	public static int update(Context context, ContentResolver resolver, Uri uri,
            ContentValues values, String where, String[] selectionArgs){
		try {
			return resolver.update(uri, values, where, selectionArgs);
		} catch (SQLiteException e) {
			// TODO Auto-generated catch block
			L.e("Catch a SQLiteException when update: " + e);
			checkSqliteException(context, e);
			return -1;
		}
	}
	
	public static int delete(Context context, ContentResolver resolver, Uri uri,
             String where, String[] selectionArgs){
		try {
			return resolver.delete(uri, where, selectionArgs);
		} catch (SQLiteException e) {
			// TODO Auto-generated catch block
			L.e("Catch a SQLiteException when delete: " + e);
			checkSqliteException(context, e);
			return -1;
		}
	}
	
	public static Uri insert(Context context, ContentResolver resolver, Uri uri,ContentValues values){
		try {
			return resolver.insert(uri, values);
		} catch (SQLiteException e) {
			// TODO Auto-generated catch block
			L.e("Catch a SQLiteException when insert: " + e);
			checkSqliteException(context, e);
			return null;
		}
	}
}
